%%%%%%%MUST BE RUN IN AN OLDER VERSION OF MATLAB (2009)%%%%%%%%

%create an array of subject numbers 
subnums=[2:12,14:20,22:37,39,40];

model='BLOCK81_LSA';
ROIs=15;

for subject = 22:length(subnums)

sub = subnums(subject);
 
    if sub < 10
        s = ['0',num2str(sub)]
            else s = num2str(sub)
    end


cd (['~/../../ncf/cushman/Regan/desert_island/desisl_',s,'/desisl_',s,'.results']);

for curroi=1:ROIs
    r=num2str(curroi)
    
    %if it is the last loop, set the mask to be all the ROIs combined.
    %Otherwise set it to be the correct ROI
    if curroi==ROIs
        maskname='full_mask';
    else maskname=['roi',r];
    end
    
    subj = init_subj('desisl', sprintf(['s', s]));
  
%%
%1. Load masks

%If it is the last loop, load the mask with all ROIs combined, otherwise
%load the mask for just this loop's ROI. 
if curroi==ROIs
    subj = load_afni_mask(subj, 'full_mask', ['desisl_',s,'_hadvdid_voxp001_corrp05_mask+orig']);
    mask=get_mat(subj, 'mask', 'full_mask');
else
    subj = load_afni_mask(subj, ['roi',r], ['desisl_',s,'_hadvdid_voxp001_corrp05_roi',r,'+orig']);
    mask=get_mat(subj, 'mask', ['roi',r]);
end


%%
%2. Load brain data

%If it hasn't been done, first pull out just the coefficient BRIK from the stats bucket
if ~exist([model,'_alltrials_coef.',s,'+orig.HEAD'],'file')
    unix(sprintf(['3dTcat -prefix ',model,'_alltrials_coef.',s,' ',model,'.stats_all.',s,'+orig[1..224]']));
end

%Then load this stats map into the subj structure
if curroi==ROIs
    subj = load_afni_pattern(subj, 'data', 'full_mask', [model,'_alltrials_coef.',s,'+orig']);
else
    subj = load_afni_pattern(subj, 'data', ['roi',r], [model,'_alltrials_coef.',s,'+orig']);
end

%%
%3. Extract brain data from subj
data = get_mat(subj,'pattern', 'data');

%Save the brain data
save (['~/../../ncf/cushman/Regan/desert_island/desisl_',s,'/desisl_',s,'.results/s',s,'_',model,'_braindata_hadvdid_',maskname,'.mat'], 'data');

clear subj
end


end